package com.actionsoft.Job;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.schedule.IJob;
import com.actionsoft.sdk.local.SDK;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 每天 08:00 自动给固定手机号发生日短信
 * 运行：java com.example.demo.BirthdaySmsJob
 */
public class BirthdayJob implements IJob {
    private static final String ACCESS_KEY_ID     = "LTAI5t6vSwUPyHPttfD9R5H7";
    private static final String ACCESS_KEY_SECRET = "Kk06ZagGSWMgAxqpcYLp9UeLZzZDKl";
    private static final String SIGN_NAME         = "北京理工大学";
    private static final String TEMPLATE_CODE     = "SMS_492445748";
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("触发了定时器!!!!!!");
        /* 真正发送短信的方法 */
        List<BO> ID = SDK.getBOAPI().query("BO_EU_XIAOYOUXINXI").addQuery("AUTH_STATUS =","已注册").list();
        for (BO bo : ID) {
            String birthdayStr = (String) bo.get("BIRTH_DATE");
            /*2. 解析成 LocalDate（假设格式 yyyy-MM-dd）*/
            birthdayStr = birthdayStr.trim();
            if (birthdayStr.isEmpty()) {System.out.println(bo.get("ALUMNI_ID")+"为空");continue;}
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate birthday = LocalDate.parse(birthdayStr, fmt);
            if (birthday.equals(LocalDate.now())) {
                String NAME = bo.get("ALUMNI_NAME").toString();
                String PHONE = bo.get("CONTACT_PHONE").toString();
                System.out.println("名字号:" + NAME + "生日就是今天" + "手机号:" + PHONE);
                try {
                    Client client = createClient();
                    String paramJson = "{\"name\":\"" + NAME + "\"}";

                    SendSmsRequest req = new SendSmsRequest()
                            .setPhoneNumbers(PHONE)
                            .setSignName(SIGN_NAME)
                            .setTemplateCode(TEMPLATE_CODE)
                            .setTemplateParam(paramJson);

                    SendSmsResponse resp = client.sendSms(req);
                    System.out.println(LocalDateTime.now() + " 生日短信发送结果：" + resp.body.code);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }


    /* 创建阿里云 Client */
    private static Client createClient() throws Exception {
        Config cfg = new Config()
                .setAccessKeyId(ACCESS_KEY_ID)
                .setAccessKeySecret(ACCESS_KEY_SECRET)
                .setEndpoint("dysmsapi.aliyuncs.com");
        return new Client(cfg);
    }

}
